package com.stu.testUser;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import com.stu.mapper.UserMapper;
import com.stu.pojo.User;
import com.stu.pojo.UserQueryVo;

public class UserTset {
	
	SqlSessionFactory sqlSessionFactory;
	@Before
	public void before() throws IOException {
		// 读取全局资源文件
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		// 创建sqlsession
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	//根据ID查找
	@Test
	public void testUser() throws IOException {

		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = sqlSession.selectOne("com.stu.mapper.UserMapper.findUserById", 1);
		System.out.println(user);
		// 关闭sqlsession
		sqlSession.close();
	}
	//模糊查找
	@Test
	public void testUser01() throws IOException {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		String state = "com.stu.mapper.UserMapper.findUserByName";
		List<User> list = sqlSession.selectList(state, "张");
		for(User lists:list) {
			System.out.println(lists);
		}
		sqlSession.close();
	}

	@Test//动态查询sql
	public void testUser02() throws IOException {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User();
		user.setId(46);
		user.setSex("男");
		List<User> list = userMapper.findUserByExample(user);
		sqlSession.close();
	}
	//动态添加sql
	@Test
	public void testUser03() throws IOException {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User();
		user.setId(47);
		user.setUsername("大大");
		user.setSex("男");
		userMapper.insertUserExample(user);
		sqlSession.commit();
		sqlSession.close();
	}
	//批量查询多个用户
		@Test
		public void testUser04() throws IOException {
			SqlSession sqlSession = sqlSessionFactory.openSession();
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			ArrayList<Integer> list1 = new ArrayList<Integer>();
			list1.add(1);
			list1.add(16);
			list1.add(25);
			UserQueryVo userQueryVo = new UserQueryVo();
			userQueryVo.setIds(list1);
			userMapper.findUserByBatch(userQueryVo);
			sqlSession.close();
			}
		//动态更新修改
		@Test
		public void testUser05() throws IOException {
			SqlSession sqlSession = sqlSessionFactory.openSession();
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			User user = new User();
			user.setId(47);
			user.setUsername("我我");
			userMapper.updateUserExample(user);
			sqlSession.commit();
			sqlSession.close();
		}
}
